
const Router = require('koa-router')
const router = new Router()
const bcrpt = require('bcryptjs')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const User = require('../../model/User')
const tools = require('../../config/tools')
const db = require('../../config/keys')
const passport = require('koa-passport')
const registerValidator = require('../../validation/register')
const loginValidator = require('../../validation/login')
router.get('/test', async (ctx, next) => {
    ctx.status = 200
    ctx.body = 'hello world'
})

//用户注册接口
router.post('/register', async (ctx, next) => {
    // 注册拦截 校验传入的value是否合法
    const { errors, isValid } = registerValidator(ctx.request.body)
    if (!isValid) {
        ctx.status = 400;
        ctx.body = errors
        return
    }
    const { email, username } = ctx.request.body
    let { password } = ctx.request.body
    const findResult = await User.find({ email })
    if (findResult && findResult.length > 0) {
        ctx.status = 500;
        ctx.body = '邮箱已经被占用'
    } else {
        const avatar = gravatar.url(email, { s: '200', r: 'pg', d: 'mm' });
        password = tools.enbcrypt(password)
        const newUser = new User({
            email,
            username,
            password,
            avatar
        })
        await newUser.save().then(user => {
            ctx.body = user;
        })
        ctx.body = newUser
    }
    await next()
})

//用户登录接口
router.post('/login', async (ctx, next) => {
    const { email, password } = ctx.request.body
    // 登录拦截 校验传入的value是否合法
    const { errors, isValid } = loginValidator(ctx.request.body)
    if (!isValid) {
        ctx.status = 400;
        ctx.body = errors
        return
    }
    const findResult = await User.find({ email })
    const user = findResult[0]
    if (findResult && findResult.length === 0) {
        ctx.status = 404;
        ctx.body = {
            email: "用户不存在！"
        }
    } else {
        const result = await bcrpt.compareSync(password, user.password)
        if (result) {
            // 登录成功
            // 返回 toekn
            const payload = {
                id: user.id,
                name: user.name,
                avatar: user.avatar
            }
            // 把用户信息带入token里面 设置私钥 设置过期时间 3600秒 也就是1小时
            const token = jwt.sign(payload, db.secretOrKey, { expiresIn: 3600 })
            ctx.status = 200
            ctx.body = {
                success: true,
                message: "登录成功!",
                // 必须以这种写法
                token: "Bearer " + token
            }
        } else {
            ctx.status = 400
            ctx.body = {
                password: '密码错误'
            }
        }
    }
    await next()
})

/**
 * 
 * passport
 */

router.get('/current',
    passport.authenticate('jwt', { session: false }),
    async (ctx, next) => {
        ctx.body = {
            id: ctx.state.user.id,
            name: ctx.state.user.username,
            email: ctx.state.user.email,
            avatar: ctx.state.user.avatar
        }
        await next()
    }
)
module.exports = router.routes()